﻿using System.Net;
using System.Net.NetworkInformation;

namespace Toolbox.util
{
    class NetUtils
    {
        // 网络工具类

        public static bool portInUse(int port, string portType)
        {
            // 检测端口是否被占用，portType只能是TCP或UDP
            bool result = false;

            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] array = null;
            if ("TCP".Equals(portType))
            {
                array = properties.GetActiveTcpListeners();
            }
            else if ("UDP".Equals(portType))
            {
                array = properties.GetActiveUdpListeners();
            }

            foreach (var ipPort in array)
            {
                if (ipPort.Port == port)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}
